//
//  YFCustomTextField.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/13.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFCustomTextField.h"

@interface YFCustomTextField()

@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIColor *boderColor;
/** code Time */
@property (nonatomic, assign)NSUInteger codeTimeCount;
@property (nonatomic, assign) LSTextfieldViewType textfieldType;
@end

@implementation YFCustomTextField


- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self initilizeUI];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initilizeUI];
    }
    return self;
}
- (void)initilizeUI {
    _codeTimeCount = 60;
    self.edgeInsets = UIEdgeInsetsMake(0, 6, 0, 6);
//    _showWhiteBoder = YES;
    _autoAdjustAlimentCenterOrLeft = YES;
    _boderColor = [UIColor whiteColor];
    [self obserInputString];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)awakeFromNib {
    [super awakeFromNib];
    [self changeTextfieldStyle:LSTextfieldViewTypePhone];
}

- (void)changeCornerRadius:(CGFloat)radius borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor {
    [self clipsCornerRadius:radius borderWidth:borderWidth borderColor:borderColor];
}

- (void)layoutSubviews {
    [super layoutSubviews];
//    if (_showWhiteBoder) {
//        [self clipsCornerRadius:0 borderWidth:1 borderColor:self.boderColor];
//    }
    if (self.showRightButton && self.rightButton != nil) {
        [self.rightButton sizeToFit];
        CGSize rightBtnSize = self.rightButton.bounds.size;
        if (self.textfieldType == LSTextfieldViewTypePassword) {
            rightBtnSize = CGSizeMake(35, 35);
        }
        CGFloat rightBtnY = (self.bounds.size.height - rightBtnSize.height) * 0.5;
        CGFloat rightBtnX = self.bounds.size.width - (rightBtnSize.width + 15);
        self.rightButton.bounds = CGRectMake(0, 0, rightBtnSize.width, rightBtnSize.height);
        self.rightView.frame = CGRectMake(rightBtnX, rightBtnY, rightBtnSize.width, rightBtnSize.height);
    }
}

- (void)obserInputString {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidBeginEdit:) name:UITextFieldTextDidBeginEditingNotification object:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidEndEdit:) name:UITextFieldTextDidEndEditingNotification object:self];
}

- (void)textFieldDidBeginEdit:(NSNotification *)noti {
    if (_autoAdjustAlimentCenterOrLeft) {
        self.textAlignment = NSTextAlignmentLeft;
    }
    if (self.textFieldDidBenginEidtHandler) {
        self.textFieldDidBenginEidtHandler(self.text);
    }
}
- (void)textFieldDidEndEdit:(NSNotification *)noti {
    if (_autoAdjustAlimentCenterOrLeft) {
        if (self.text.length > 0) {
            self.textAlignment = NSTextAlignmentLeft;
        }else {
            self.textAlignment = NSTextAlignmentCenter;
        }
    }
    if (self.textFieldDidEndEidtHandler) {
        self.textFieldDidEndEidtHandler(self.text);
    }
}

- (void)setPlaceHolderAlignment:(NSTextAlignment)placeHolderAlignment {
    _placeHolderAlignment = placeHolderAlignment;
    if (self.text.length == 0) {
        self.textAlignment = placeHolderAlignment;
    }
}

- (void)changeTextfieldStyle:(LSTextfieldViewType)textfieldType {
    self.textfieldType = textfieldType;
    self.maxLength = MAXINTERP;
    switch (textfieldType) {
        case LSTextfieldViewTypeNormal:{
            self.keyboardType = UIKeyboardTypeDefault;
        }
            break;
        case LSTextfieldViewTypePhone:{
            self.keyboardType = UIKeyboardTypeNumberPad;
            self.maxLength = 11;
        }
            break;
        case LSTextfieldViewTypeEmail:{
            self.keyboardType = UIKeyboardTypeEmailAddress;
        }
            break;
        case LSTextfieldViewTypePassword:{
            self.keyboardType = UIKeyboardTypeDefault;
            self.showRightButton = YES;
            self.secureTextEntry = YES;
            [self.rightButton setImage:[UIImage imageNamed:@"login_closeEye"] forState:UIControlStateNormal];
            [self.rightButton setTitle:@"" forState:UIControlStateNormal];
            _rightButton.userInteractionEnabled = YES;
             self.maxLength = 20;
        }
            break;
        case LSTextfieldViewTypeVerifyCode:{
            self.keyboardType = UIKeyboardTypeNumberPad;
            self.showRightButton = YES;
            [self.rightButton setImage:nil forState:UIControlStateNormal];
            [self.rightButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            _rightButton.userInteractionEnabled = YES;
        }
            break;
    }
}

- (void)setShowRightButton:(BOOL)showRightButton {
    _showRightButton = showRightButton;
    if (showRightButton) {
        self.rightButton.hidden = NO;
        self.rightViewMode = UITextFieldViewModeAlways;
    }else {
        self.rightView = nil;
        _rightButton = nil;
    }
}


- (void)textFieldChanged:(NSNotification *)sender
{
    UITextField *textField = (UITextField *)sender.object;
    NSString *toBeString = textField.text;
    if (![self regExpCheckForText:toBeString]) {
        textField.text = [toBeString stringByReplacingCharactersInRange:NSMakeRange(toBeString.length - 1, 1) withString:@""];
    }
    if (self.textChangeHandler) {
        self.textChangeHandler(self.text);
    }
    NSString *lang = [textField.textInputMode primaryLanguage];
    if ([lang isEqualToString:@"zh-Hans"])// 简体中文输入
    {
        //获取高亮部分
        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position)
        {
            if (toBeString.length > self.maxLength)
            {
                textField.text = [toBeString substringToIndex:self.maxLength];
            }
        }
        
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else
    {
        if (toBeString.length > self.maxLength)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:self.maxLength];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:self.maxLength];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, self.maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

#pragma mark - 右侧按钮
- (void)rightButtonClick:(UIButton *)sender {
    if (self.clickRightButtonHandler) {
        self.clickRightButtonHandler(self.text);
    }
    if (self.textfieldType == LSTextfieldViewTypeVerifyCode) {
        [self timer];
    }else if (self.textfieldType == LSTextfieldViewTypePassword){
        [self changeShowCode];
    }
}

- (void)changeShowCode {
    if (self.showRightButton) {
        if (self.isSecureTextEntry){
            self.secureTextEntry = NO;
             [self.rightButton setImage:[UIImage imageNamed:@"login_openEye"] forState:UIControlStateNormal];
        }else {
            self.secureTextEntry = YES;
            [self.rightButton setImage:[UIImage imageNamed:@"login_closeEye"] forState:UIControlStateNormal];
        }
        [self.rightButton setTitle:@"" forState:UIControlStateNormal];
    }
}

// 数据验证
- (BOOL)regExpCheckForText:(NSString *)text {
    if (self.regExpCheck.length > 1 && text.length >= 1) {
        NSString *regex = self.regExpCheck;
        NSPredicate *emailVerify = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        return [emailVerify evaluateWithObject:text];
    }
    return YES;
}

- (UIButton *)rightButton {
    if (_rightButton == nil && self.rightView == nil) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightButton addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_rightButton setTitleColor:kTLightGray999 forState:UIControlStateNormal];
        _rightButton.titleLabel.font = [UIFont systemFontOfSize:11];
        _rightButton.titleLabel.textColor = [UIColor grayColor];
        _rightButton.hidden = YES;
        _rightButton.bounds = CGRectMake(0, 0, 30, 30);
        _rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        self.rightView = _rightButton;
    }
    return _rightButton;
}
- (NSInteger)maxLength {
    if (_maxLength <= 0) {
        return MAXINTERP;
    }
    return _maxLength;
}

- (void)updateVerifyCodeTime {
    _codeTimeCount--;
    if (_codeTimeCount == 0) {
        _codeTimeCount = 60;
        [self.rightButton setTitle:[NSString stringWithFormat:@"%zds",_codeTimeCount] forState:UIControlStateNormal];
        _rightButton.titleLabel.textColor = [UIColor blackColor];
        _rightButton.userInteractionEnabled = NO;
    }else {
        [self.timer invalidate];
        self.timer = nil;
        [self.rightButton setTitle:@"重新获取" forState:UIControlStateNormal];
        _rightButton.titleLabel.textColor = [UIColor grayColor];
        _rightButton.userInteractionEnabled = YES;
    }
}

- (NSTimer *)timer {
    if (_timer == nil) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateVerifyCodeTime) userInfo:self repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
    return _timer;
}

@end
